package com.irdstudio.devops.console.service.impl;

import java.io.*;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import com.irdstudio.bfp.console.dao.domain.SubsCodeBase;
import com.irdstudio.devops.console.dao.SysDeployInfoDao;
import com.irdstudio.sdk.beans.core.util.KeyUtil;
import com.irdstudio.sdk.beans.core.util.PropertiesUtil;
import com.irdstudio.sdk.beans.core.util.TimeUtil;
import com.irdstudio.sdk.beans.ssh.utils.RemoteShellClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.irdstudio.devops.console.service.facade.SysDeployInfoService;
import com.irdstudio.devops.console.dao.domain.SysDeployInfo;
import com.irdstudio.devops.console.service.vo.SysDeployInfoVO;
import com.irdstudio.sdk.beans.core.base.FrameworkService;
/**
 * <p>ServiceImpl: 系统部署信息				<p>
 * @author zjj
 * @date 2020-10-27
 */
@Service("sysDeployInfoServiceImpl")
public class SysDeployInfoServiceImpl implements SysDeployInfoService, FrameworkService {
	
	private static Logger logger = LoggerFactory.getLogger(SysDeployInfoServiceImpl.class);

	@Autowired
	private SysDeployInfoDao sysDeployInfoDao;

	/**
	 * 新增操作
	 */
	@Override
	public int insertSysDeployInfo(SysDeployInfoVO inSysDeployInfoVo) {
		logger.debug("当前新增数据为:"+ inSysDeployInfoVo.toString());
		int num = 0;
		try {
			SysDeployInfo sysDeployInfo = new SysDeployInfo();
			beanCopy(inSysDeployInfoVo, sysDeployInfo);
			sysDeployInfo.setOperUserid("admin");
			sysDeployInfo.setOperTime(TimeUtil.getCurrentDate());
			sysDeployInfo.setAppDeployId(KeyUtil.createUUIDKey());
			num = sysDeployInfoDao.insertSysDeployInfo(sysDeployInfo);
		} catch (Exception e) {
			logger.error("新增数据发生异常!", e);
			num = -1;
		}
		logger.debug("当前新增数据条数为:"+ num);
		return num;
	}

	/**
	 * 删除操作
	 */
	@Override
	public int deleteByPk(SysDeployInfoVO inSysDeployInfoVo) {
		logger.debug("当前删除数据条件为:"+ inSysDeployInfoVo);
		int num = 0;
		try {
			SysDeployInfo sysDeployInfo = new SysDeployInfo();
			beanCopy(inSysDeployInfoVo, sysDeployInfo);
			num = sysDeployInfoDao.deleteByPk(sysDeployInfo);
		} catch (Exception e) {
			logger.error("删除数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inSysDeployInfoVo +"删除的数据条数为"+ num);
		return num;
	}


	/**
	 * 更新操作
	 */
	@Override
	public int updateByPk(SysDeployInfoVO inSysDeployInfoVo) {
		logger.debug("当前修改数据为:"+ inSysDeployInfoVo.toString());
		int num = 0;
		try {
			SysDeployInfo sysDeployInfo = new SysDeployInfo();
			beanCopy(inSysDeployInfoVo, sysDeployInfo);
			num = sysDeployInfoDao.updateByPk(sysDeployInfo);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ inSysDeployInfoVo +"修改的数据条数为"+ num);
		return num;
	}

	/**
	 *更新subsCode
	 * @return
	 */
	@Override
	public int updateBySubsCode(SubsCodeBase subsCodeBase) {
		logger.debug("当前修改数据为:"+ subsCodeBase.toString());
		int num = 0;
		try {
			num = sysDeployInfoDao.updateBySubsCode(subsCodeBase);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ subsCodeBase.getOldSubsCode() +"修改的数据条数为"+ num);
		return 0;
	}

	@Override
	public int updateAppName(SysDeployInfoVO sysDeployInfo) {
		logger.debug("当前修改数据为:"+ sysDeployInfo.toString());
		int num = 0;
		try {
			SysDeployInfo querySysDeployInfo = new SysDeployInfo();
			beanCopy(sysDeployInfo, querySysDeployInfo);
			num = sysDeployInfoDao.updateAppName(querySysDeployInfo);
		} catch (Exception e) {
			logger.error("修改数据发生异常!", e);
			num = -1;
		}
		logger.debug("根据条件:"+ sysDeployInfo.getAppName() +"修改的数据条数为"+ num);
		return 0;
	}

	/**
	 * 查询操作
	 */
	@Override
	public SysDeployInfoVO queryByPk(SysDeployInfoVO inSysDeployInfoVo) {
		
		logger.debug("当前查询参数信息为:"+ inSysDeployInfoVo);
		try {
			SysDeployInfo querySysDeployInfo = new SysDeployInfo();
			beanCopy(inSysDeployInfoVo, querySysDeployInfo);
			SysDeployInfo queryRslSysDeployInfo = sysDeployInfoDao.queryByPk(querySysDeployInfo);
			if (Objects.nonNull(queryRslSysDeployInfo)) {
				SysDeployInfoVO outSysDeployInfoVo = beanCopy(queryRslSysDeployInfo, new SysDeployInfoVO());
				logger.debug("当前查询结果为:"+ outSysDeployInfoVo.toString());
				return outSysDeployInfoVo;
			} else {
				logger.debug("当前查询结果为空!");
			}
		} catch (Exception e) {
			logger.error("查询数据发生异常!", e);
		}
		return null;
	}


	/**
	 * 查询用户权限数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<SysDeployInfoVO> queryAllOwner(SysDeployInfoVO sysDeployInfoVo) {

		logger.debug("当前查询本人所属数据信息的参数信息为:");
		List<SysDeployInfoVO> list = null;
		try {
			List<SysDeployInfo> sysDeployInfos = sysDeployInfoDao.queryAllOwnerByPage(sysDeployInfoVo);
			logger.debug("当前查询本人所属数据信息的结果集数量为:"+ sysDeployInfos.size());
			pageSet(sysDeployInfos, sysDeployInfoVo);
			list = (List<SysDeployInfoVO>) beansCopy(sysDeployInfos, SysDeployInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构权限数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<SysDeployInfoVO> queryAllCurrOrg(SysDeployInfoVO sysDeployInfoVo) {

		logger.debug("当前查询本人所属机构数据信息的参数信息为:");
		List<SysDeployInfo> sysDeployInfos = sysDeployInfoDao.queryAllCurrOrgByPage(sysDeployInfoVo);
		logger.debug("当前查询本人所属机构数据信息的结果集数量为:"+sysDeployInfos.size());
		List<SysDeployInfoVO> list = null;
		try {
			pageSet(sysDeployInfos, sysDeployInfoVo);
			list = (List<SysDeployInfoVO>) beansCopy(sysDeployInfos, SysDeployInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}


	/**
	 * 查询当前机构及下属机构权限数据
	 */
	@Override
	@SuppressWarnings("unchecked")
	public List<SysDeployInfoVO> queryAllCurrDownOrg(SysDeployInfoVO sysDeployInfoVo) {

		logger.debug("当前查询本人所属机构及以下数据信息的参数信息为:");
		List<SysDeployInfo> sysDeployInfos = sysDeployInfoDao.queryAllCurrDownOrgByPage(sysDeployInfoVo);
		logger.debug("当前查询本人所属机构及以下数据信息的结果集数量为:"+ sysDeployInfos.size());
		List<SysDeployInfoVO> list = null;
		try {
			pageSet(sysDeployInfos, sysDeployInfoVo);
			list = (List<SysDeployInfoVO>) beansCopy(sysDeployInfos, SysDeployInfoVO.class);
		} catch (Exception e) {
			logger.error("数据转换出现异常!", e);
		}
		
		return list;
	
	}
	@Override
	@Async
	public void deploymentApplication(SysDeployInfoVO inSysDeployInfoVo){
		// 1.针对每台服务器发布应用
		logger.info("开始部署应用:"+inSysDeployInfoVo.getAppName()+"到服务器:"+inSysDeployInfoVo.getEcsName()+",端口:"+inSysDeployInfoVo.getAppPort());
		// 远程操作Linux服务器
		RemoteShellClient rsc = new RemoteShellClient(inSysDeployInfoVo.getEcsIp(),
				inSysDeployInfoVo.getEcsLoginUser(), inSysDeployInfoVo.getEcsLoginPwd());
		boolean loginFlag = rsc.login();

		if (!loginFlag) {
			logger.info("登陆服务器失败");
		}else {
			// 如果不存在该目录则进行创建并初始化
			String localAgentPath = inSysDeployInfoVo + File.separator + "agent" + File.separator;
			if (!rsc.getFileProperties("/agent")) {
				// 2.1.创建目录
				rsc.exec("mkdir /agent");
				// 2.2.上传tomcat包到agent目录
				rsc.putFile(localAgentPath + "apache-tomcat-8.5.59.tar.gz", "/agent");
				// 2.3.上传agent所需要的sh到服务器
				rsc.putFile(localAgentPath + "startTomcatApp.sh", "/agent");
				// 2.4.解压tomcat
				// rsc.exec("gzip -d d://apptemplate//agent//apache-tomcat-8.5.59.tar.gz");
				// 2.5.更改sh脚本的权限
				rsc.exec("chmod 777 /agent/startTomcatApp.sh");
			}
			// 如果存在agent,则直接上传应用包并启动应用
			String localProjectWar = inSysDeployInfoVo.getAppDeployPath();
			logger.info("本地war包:"+localProjectWar);
			rsc.login();
			rsc.putFile(localProjectWar, "/agent");
			logger.info("执行命令 " + "/agent/startTomcatApp.sh " + inSysDeployInfoVo.getAppName() + " " + inSysDeployInfoVo.getAppPort());
			int status = rsc.exec("/agent/startTomcatApp.sh " + inSysDeployInfoVo.getAppName() + " " + inSysDeployInfoVo.getAppPort());
			if (status == -1) {
				logger.info("执行发布命令 /agent/startTomcatApp.sh 状态:"+status);
			}
			if (status!=-1){
				insertSysDeployInfo(inSysDeployInfoVo);
			}
		}
		rsc.exit();
	}

	@Override
	public String readLogFile(String bpaSerialNo){
		StringBuffer buffer = new StringBuffer();
		String encoding = "UTF-8";

		String logPath =PropertiesUtil.getPropertyByKey("application", "agent.batch.log.path");
		String fullLogFileName = logPath + File.separator + bpaSerialNo + ".log";
		logger.debug("文件地址:"+fullLogFileName);
		try {
			BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(new FileInputStream(fullLogFileName),encoding));
			String lineTxt;
			while ((lineTxt = bufferedReader.readLine())!=null){
				buffer.append(lineTxt + "\n");
			}
			bufferedReader.close();
		} catch (UnsupportedEncodingException e) {
			logger.error("读取文件转码异常"+e);
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			logger.error("读取文件错误"+e);
			e.printStackTrace();
		} catch (IOException e) {
			logger.error("读取文件内容错误"+e);
			e.printStackTrace();
		}
		return buffer.toString();
	}
}
